package ctu.kfad.run.memory;

import java.util.Arrays;

public class MemoryManager {

    public static final int MEMORY_SIZE = 10000;

    private byte[] memory1 = new byte[MEMORY_SIZE];
    private byte[] memory2 = new byte[MEMORY_SIZE];

    private byte[] mainMemory = memory1;
    private byte[] futureMemory = memory2;

    private int memoryTail = 0;

    public int allocateSpace(int size) {
        final int start = memoryTail;
        memoryTail += size;
        if (memoryTail > mainMemory.length) {
            return -1;
        }
        return start;
    }

    public byte[] readMemory(int startIndex, int size) {
        return Arrays.copyOfRange(mainMemory, startIndex, startIndex + size);
    }

    public void writeToMemory(int startIndex, byte[] value) {
        System.arraycopy(value, 0, mainMemory, startIndex, value.length);
    }

    public void swapMemory() {
        memoryTail = 0;
        if (mainMemory == memory1) {
            mainMemory = memory2;
            futureMemory = memory1;
        } else {
            mainMemory = memory1;
            futureMemory = memory2;
        }
    }


    public int copyDataFromOldMemory(int referenceToMemory, int totalSize) {
        final int newReferenceInMemory = allocateSpace(totalSize);
        System.arraycopy(futureMemory, referenceToMemory, mainMemory, newReferenceInMemory, totalSize);
        return newReferenceInMemory;
    }


    public void cleanMemory() {
        final byte b = new Integer(0).byteValue();
        Arrays.fill(futureMemory, b);
    }
}
